package development.app.football;

import iplayparticle.view.iplayparticleResources;

import java.util.Vector;

import state.Clip;
import state.DrawListener;
import state.GameAlert;
import state.GameConstants;
import state.GameForm;
import state.GameGlobal;
import state.GameImage;
import state.Graphics;
import state.Key;
import state.Sprite;
import state.component.Checkbox;
import state.component.Event;
import state.component.EventListener;
import state.component.GameScrollBar;
import state.component.MultiTab;
import state.component.TextField;
import state.font.FontManager;
import state.font.ImageText;
import state.socket.DataPackage;
import state.socket.MapDataPackage;
import state.util.GameColor;
import state.util.GameStringUtils;
import state.util.Hashtable;
import state.util.NumberUtil;
import state.util.GameBoolean;
import state.util.array.StringArray;
import development.Constants;
import development.DrawUtils;
import development.Global;
import development.bean.Category;
import development.group.FrmGroupBongDaXoSo;
import development.group.FrmGroupMenu;
import development.group.FrmGroupNapXuAndExchangeGold;

public class FrmBongDaBetting extends GameForm implements EventListener {

  public static final int FOOTBALL_PROGRAM_PHASE_BETTING_ONLINE_REQUEST = 500;
  public static final int FOOTBALL_PROGRAM_PHASE_BETTING_ONLINE_RESPONSE = 501;

  public static final int FOOTBALL_BETTING_OBJECT_ONLINE_REQUEST = 502;
  public static final int FOOTBALL_BETTING_OBJECT_ONLINE_RESPONSE = 503;

  public static final int FOOTBALL_BETTING_SUBMIT_ONLINE_REQUEST = 504;
  public static final int FOOTBALL_BETTING_SUBMIT_ONLINE_RESPONSE = 505;

  private ImageText text8;
  private ImageText text11;
  private int categoryIndex;
  private String formType;
  private Hashtable logAction = null;
  private int currentAction;

  private int CATEGORY_IMAGE_HEIGHT;
  private int dy;
  private final int DEFAULT_TEXT_X = 5;
  private GameScrollBar scrollBar;
  private Clip textView; // Là khung nhìn để vẽ đoạn text ra
  private Vector categories;

  private TextField txtBetMoney;
  private GameImage buttonImage;
  private Sprite betButtonSprite;

  private StringArray PHASE_NAME;
  private Hashtable parameters;

  private final String WAITING_MESSAGE = "Xin chờ trong giây lát...";
  public static GameForm backTab;
  private static GameForm singleton;

  public static GameForm instance() {
    if (singleton == null) {
      singleton = new FrmBongDaBetting();
    }
    return singleton;
  }

  public void init(Hashtable parameters1) {
    this.parameters = parameters1;
    text8 = FontManager.getFont(FontManager.FONT_SIZE_8);
    text11 = FontManager.getFont(FontManager.FONT_SIZE_11);
    txtBetMoney = new TextField(_manager, TextField.CONSTRAINT_NUMERIC, null);
    txtBetMoney.setSize(GameConstants.SCREEN_WIDTH / 2 + 7, text8.getHeight());
    txtBetMoney.setVisible(false);
    buttonImage = new GameImage(iplayparticleResources.image_button, null, null);
    betButtonSprite = new Sprite(null, _manager, 0, 0, Constants.TOP_LEFT_ANCHOR);
    betButtonSprite.setImage(buttonImage);
    betButtonSprite.setAnchor(Constants.TOP_LEFT_ANCHOR);
    betButtonSprite.setVisible(false);
    betButtonSprite.setDrawListener(new DrawListener() {
      public void paint(Sprite source, Graphics g) {
        text8.drawString2(g, "Đặt giá", GameColor.WHITE_CODE, source.getRealX() + source.getWidth() / 2, source.getRealY() + 2, Constants.TOP_HCENTER_ANCHOR);
      }
    });
    categories = new Vector();
    logAction = new Hashtable();
    currentAction = 1;
    formType = "phase";
    categoryIndex = 0;

    CATEGORY_IMAGE_HEIGHT = Global.getDefaultAvatar().getHeight();
    dy = DrawUtils.getTopBarHeight();
    textView = new Clip(DEFAULT_TEXT_X, dy, Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT - dy - 10); // Là khung nhìn để vẽ đoạn text ra
    scrollBar = new GameScrollBar(Constants.SCREEN_WIDTH - 5, 25, 5, Constants.SCREEN_HEIGHT - 50, textView, _manager);

    if (parameters1 != null) {
      GameBoolean isRequestVotingObject = (GameBoolean) parameters1.get("requestVotingObject");
      if (isRequestVotingObject != null && isRequestVotingObject.booleanValue()) {
        Vector param = new Vector();
        param.addElement(parameters1.get("phaseId"));
        request(FOOTBALL_BETTING_OBJECT_ONLINE_REQUEST, param);
        clearCategory();
      } else {
        String program = (String) parameters1.get("program");
        Vector value = new Vector();
        value.addElement(program);
        request(FOOTBALL_PROGRAM_PHASE_BETTING_ONLINE_REQUEST, value);
        clearCategory();
      }
    }
    _manager.enableTouchPad();
    DrawUtils.setBottomBar(_manager, "Menu chính", "Chọn", "Trở về");
  }

  public void draw(Graphics g) {
    DrawUtils.drawAppBackground(g);
    if (categories.isEmpty()) {
      text8.drawString2(g, WAITING_MESSAGE, GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH / 2, GameConstants.SCREEN_HEIGHT / 2, GameConstants.TOP_HCENTER_ANCHOR);
    }
    if (formType.equals("FOOTBALL_TAI_XIU") || formType.equals("FOOTBALL_KQ") || formType.equals("FOOTBALL_TS")) {
      drawBettingObject(g);
    }
    if (formType.equals("phase")) {
      drawBettingProgramPhase(g);
    }
    drawMenu(g);
  }

  private void drawMenu(Graphics g) {
    DrawUtils.getBottomBar(_manager).setCenterLabel("Chọn");
    if (!formType.equals("phase")) {
      if (txtBetMoney.isFocused()) {
        DrawUtils.getBottomBar(_manager).setRightLabel("Xóa");
      } else {
        DrawUtils.getBottomBar(_manager).setRightLabel("Trở về");
      }
    }
    if (!formType.equals("phase")) {
      DrawUtils.getBottomBar(_manager).setLeftLabel("Menu chính");
    }
    if (formType.equals("phase")) {
      DrawUtils.getBottomBar(_manager).setRightLabel("Trở về");
    }
  }

  private void drawBettingObject(Graphics g) {
    int textY = dy;
    int index = 0;
    g.setColor(0xA9A9A9);
    g.fillRect(0, textY, GameConstants.SCREEN_WIDTH, text11.getHeight());
    g.drawRect(0, textY, GameConstants.SCREEN_WIDTH, text11.getHeight());
    text11.drawString2(g, "Thông tin trận đấu", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH / 2, textY, GameConstants.TOP_HCENTER_ANCHOR);
    textY = textY + 20;
    for (int i = 0; i < PHASE_NAME.len(); i++) {
      text8.drawString2(g, PHASE_NAME.get(i), GameColor.YELLOW_CODE, 5, textY, GameConstants.TOP_LEFT_ANCHOR);
      textY = textY + 20;
    }
    g.setColor(0xA9A9A9);
    g.fillRect(0, textY, GameConstants.SCREEN_WIDTH, text11.getHeight());
    g.drawRect(0, textY, GameConstants.SCREEN_WIDTH, text11.getHeight());
    text11.drawString2(g, "Chọn kèo", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH / 2, textY, GameConstants.TOP_HCENTER_ANCHOR);
    textY = textY + 20;
    for (int i = 0; i < categories.size(); i++) {
      index++;
      Category category = (Category) categories.elementAt(i);
      if (categoryIndex == index) {
        category.cb.setFocused(true);
      } else {
        category.cb.setFocused(false);
      }
      category.cb.setPosition(0, textY);
      category.cb.draw(g);
      textY = textY + 20;
    }
    g.setColor(0xA9A9A9);
    g.fillRect(0, textY, GameConstants.SCREEN_WIDTH, text11.getHeight());
    g.drawRect(0, textY, GameConstants.SCREEN_WIDTH, text11.getHeight());
    text11.drawString2(g, "Đặt cược", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH / 2, textY, GameConstants.TOP_HCENTER_ANCHOR);
    textY = textY + 30;
    text8.drawString2(g, "Số $: ", GameColor.YELLOW_CODE, 5, textY, GameConstants.TOP_LEFT_ANCHOR);
    txtBetMoney.setPosition(text8.stringWidth("Số $: ") + 5, textY);
    txtBetMoney.draw(g);
    betButtonSprite.setPosition(txtBetMoney.getRealX() + txtBetMoney.getWidth() + 5, textY - 3);
    betButtonSprite.setVisible(true);
  }

  private void drawBettingProgramPhase(Graphics g) {
    int textY = dy;
    int index = 0;
    for (int i = 0; i < categories.size(); i++) {
      Category category = (Category) categories.elementAt(i);
      for (int j = 0; j < category.exParam.size(); j++) {
        if (categoryIndex == index) {
          g.setColor(0x53A4CF);
          g.fillRect(0, textY, GameConstants.SCREEN_WIDTH, text8.getHeight() + 25);
          text8.drawString3(g, (String) category.exParam.elementAt(j), GameColor.YELLOW_CODE, DEFAULT_TEXT_X, textY, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
        } else {
          text8.drawString3(g, (String) category.exParam.elementAt(j), GameColor.YELLOW_CODE, DEFAULT_TEXT_X, textY, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
        }
        textY = textY + 20;
      }
      if (category.fee > 0) {
        text8.drawString3(g, "Số $ chơi tối thiểu: " + category.fee + "$", GameColor.YELLOW_CODE, DEFAULT_TEXT_X, textY, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
        textY = textY + 20;
      }
      if (categoryIndex == index) {
        g.setColor(0x53A4CF);
        g.fillRect(0, textY, GameConstants.SCREEN_WIDTH, text8.getHeight() + 5);
        if (category.status == 1) {
          text8.drawString3(g, "Chơi ngay >>", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH - 5, textY, GameConstants.TOP_RIGHT_ANCHOR, scrollBar);
        } else {
          text8.drawString3(g, "Đã kết thúc >>", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH - 5, textY, GameConstants.TOP_RIGHT_ANCHOR, scrollBar);
        }
      } else {
        if (category.status == 1) {
          text8.drawString3(g, "Chơi ngay >>", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH - 5, textY, GameConstants.TOP_RIGHT_ANCHOR, scrollBar);
        } else {
          text8.drawString3(g, "Đã kết thúc >>", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH - 5, textY, GameConstants.TOP_RIGHT_ANCHOR, scrollBar);
        }
      }
      textY = textY + 20;
      g.setColor(0xC0C0C0);
      g.drawLine(0, textY, GameConstants.SCREEN_WIDTH, textY);
      index++;
    }
  }
  
  public void onActionPerform(Event event) {
    if (MultiTab.OPEN_TAB_EVENT.equals(event.getAction())) {
      DrawUtils.setBottomBar(_manager, "Menu chính", "Chọn", "Trở về");
      return;
    }
  }

  public void onRecieveData(DataPackage dataPackage) {
    int header = dataPackage.getHeader();
    MapDataPackage mapDataPackage = MapDataPackage.getMapPackage(dataPackage);
    if (mapDataPackage.getString("type") != null && !mapDataPackage.getString("type").equals("")) {
      formType = mapDataPackage.popString("type");
    }
    Category category = null;
    GameGlobal.systemCanvas.hideAlert();
    switch (header) {
    case FOOTBALL_PROGRAM_PHASE_BETTING_ONLINE_RESPONSE:
      category = new Category();
      category.id = mapDataPackage.getString("phaseId");
      category.code = mapDataPackage.getString("code");
      category.name = mapDataPackage.getString("name");
      category.fee = NumberUtil.parseInt(mapDataPackage.getString("fee"));
      StringArray arrName = GameStringUtils.split(category.name, "\n");

      // Hien thi tung dong
      for (int i = 0; i < arrName.len(); i++) {
        category.exParam.addElement(arrName.get(i));
      }
      category.exParam.addElement("Thời gian dự đoán:");
      category.exParam.addElement(mapDataPackage.getString("startTime") + " đến " + mapDataPackage.getString("endTime"));
      category.hasChild = false;
      category.image = Global.getDefaultAvatar();
      category.status = NumberUtil.parseInt(mapDataPackage.getString("status"));
      CATEGORY_IMAGE_HEIGHT = category.image.getHeight();
      categories.addElement(category);
      break;
    case FOOTBALL_BETTING_OBJECT_ONLINE_RESPONSE:
      category = new Category();
      category.id = mapDataPackage.getString("votingObjectId");
      category.code = mapDataPackage.getString("phaseId");
      category.cb = new Checkbox(_manager, this, Constants.CHECK_BOX_STYLE_APP, 0, 0);
      category.cb.setLabel(mapDataPackage.getString("name"));
      category.cb.setAnchor(GameConstants.TOP_LEFT_ANCHOR);
      category.cb.setVisible(true);
      txtBetMoney.setVisible(true);
      PHASE_NAME = GameStringUtils.split(mapDataPackage.getString("phaseName"), "\n");
      categories.addElement(category);
      break;
    case FOOTBALL_BETTING_SUBMIT_ONLINE_RESPONSE:
      int status = mapDataPackage.getInt("status");
      if (status == -1) {
        Global.alert.showAlert3(this, GameAlert.OK_TYPE, StringArray.create1( "Có sự cố xảy ra", "Hãy thử lại sau ít phút" ));
      } else {
        Global.alert.showAlert3(this, GameAlert.OK_TYPE, StringArray.create1( "Bạn đã cược thành công", "Chúc bạn may mắn" ));
      }
      break;
    }
  }

  public void keyReleased(int keyCode) {
    switch (keyCode) {
    case Key.DOWN:
      if (!formType.equals("phase")) {
        if (categoryIndex < categories.size() + 2) {
          categoryIndex++;
          dy -= 5;
        }
        if (categoryIndex == categories.size() + 1) {
          txtBetMoney.setFocused(true);
        } else {
          txtBetMoney.setFocused(false);
        }
        if (categoryIndex == categories.size() + 2) {
          betButtonSprite.setDrawListener(new DrawListener() {
            public void paint(Sprite source, Graphics g) {
              text8.drawString2(g, "Đặt giá", GameColor.YELLOW_CODE, source.getRealX() + source.getWidth() / 2, source.getRealY() + 2, Constants.TOP_HCENTER_ANCHOR);
            }
          });
        } else {
          betButtonSprite.setDrawListener(new DrawListener() {
            public void paint(Sprite source, Graphics g) {
              text8.drawString2(g, "Đặt giá", GameColor.WHITE_CODE, source.getRealX() + source.getWidth() / 2, source.getRealY() + 2, Constants.TOP_HCENTER_ANCHOR);
            }
          });
        }
      } else {
        if (categoryIndex < categories.size() - 1) {
          categoryIndex++;
        }
        if (categories.size() * (CATEGORY_IMAGE_HEIGHT + 25) < GameConstants.SCREEN_HEIGHT - DrawUtils.getBottomBarHeight()) {
          return;
        }
        if (scrollBar.canScrollUp()) {
          dy = dy - (CATEGORY_IMAGE_HEIGHT + 25);
        }
      }
      break;
    case Key.UP:
      if (!formType.equals("phase")) {
        if (categoryIndex > 0) {
          categoryIndex--;
          dy += 5;
        }
        if (categoryIndex < categories.size()) {
          txtBetMoney.setFocused(false);
        } else if (categoryIndex == categories.size() + 1) {
          txtBetMoney.setFocused(true);
        }
        if (categoryIndex == categories.size() + 2) {
          betButtonSprite.setDrawListener(new DrawListener() {
            public void paint(Sprite source, Graphics g) {
              text8.drawString2(g, "Đặt giá", GameColor.YELLOW_CODE, source.getRealX() + source.getWidth() / 2, source.getRealY() + 2, Constants.TOP_HCENTER_ANCHOR);
            }
          });
        } else {
          betButtonSprite.setDrawListener(new DrawListener() {
            public void paint(Sprite source, Graphics g) {
              text8.drawString2(g, "Đặt giá", GameColor.WHITE_CODE, source.getRealX() + source.getWidth() / 2, source.getRealY() + 2, Constants.TOP_HCENTER_ANCHOR);
            }
          });
        }
      } else {
        if (categoryIndex > 0) {
          categoryIndex--;
        }
        if (scrollBar.canScrollDown()) {
          dy = dy + (CATEGORY_IMAGE_HEIGHT + 25);
        }
      }
      break;
    case Key.FIRE:
      if (formType.equals("phase")) {
        currentAction++;
        Category category = (Category) categories.elementAt(categoryIndex);
        if (Global.currentUser.getMoney() < category.fee) {
          Global.alert.showAlert1(this, GameAlert.YES_NO_TYPE, StringArray.create1( "Bạn không đủ $ để chơi", "Bạn có muốn nạp $ không?" ), 100);
          return;
        }
        parameters.put("phaseId", category.id);
        if (category.status == 1) {
          parameters.put("requestVotingObject", new GameBoolean(true));
        } else {
          parameters.put("requestVotingObject", new GameBoolean(false));
        }
        FrmGroupBongDaXoSo frmGroupBongDaXoSo = (FrmGroupBongDaXoSo) FrmGroupBongDaXoSo.instance();
        frmGroupBongDaXoSo.getMultiTab().setTab(1, FrmBettingMenu.instance(), parameters);
        return;
      } else {
        if (categoryIndex > 0 && categoryIndex <= categories.size()) {
          Category category = (Category) categories.elementAt(categoryIndex - 1);
          if (category.cb.isChecked()) {
            category.cb.setChecked(false);
          } else {
            category.cb.setChecked(true);
            for (int i = 0; i < categories.size(); i++) {
              Category cat = (Category) categories.elementAt(i);
              if (!cat.cb.getLabel().equals(category.cb.getLabel())) {
                cat.cb.setChecked(false);
              }
            }
          }
        } else {
          if (txtBetMoney.isFocused()) {
            txtBetMoney.pointerReleased(txtBetMoney, txtBetMoney.getRealX(), txtBetMoney.getRealY());
          }
          if (categoryIndex == categories.size() + 2) {
            if (validateBet()) {
              for (int i = 0; i < categories.size(); i++) {
                Category category = (Category) categories.elementAt(i);
                if (category.cb.isChecked()) {
                  Vector param = new Vector();
                  // votingObjectId
                  param.addElement(category.id);
                  // phaseId
                  param.addElement(category.code);
                  // bet money
                  param.addElement(txtBetMoney.getText());
                  request(FOOTBALL_BETTING_SUBMIT_ONLINE_REQUEST, param);
                  Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(10000);
                }
              }
            }
          }
        }
      }
      break;
    case Key.SOFT_LEFT:
      if (!formType.equals("phase")) {
        GameGlobal.nextState(FrmGroupMenu.instance(), null);
      }
      break;
    case Key.SOFT_RIGHT:
      if (txtBetMoney.isFocused()) {
        txtBetMoney.deleteLastChar();
      } else {
        if (currentAction > 1) {
          clearCategory();
          back();
          Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(10000);
        } else {
          parameters.put("category", "BETTING_ONLINE");
          FrmGroupBongDaXoSo frmGroupBongDaXoSo = (FrmGroupBongDaXoSo) FrmGroupBongDaXoSo.instance();
          frmGroupBongDaXoSo.getMultiTab().setTab(1, backTab, parameters);
        }
      }
      break;
    default:
      if (txtBetMoney.isFocused()) {
        txtBetMoney.keyReleased1(keyCode);
      }
      break;
    }
  }

  public void alertEventPerform(int alertType, int eventType, int alertId) {
    if (alertId == 100 && eventType == GameAlert.YES_BUTTON) {
      FrmGroupNapXuAndExchangeGold.backForm = FrmGroupBongDaXoSo.instance();
      Global.nextState(FrmGroupNapXuAndExchangeGold.instance(), parameters);
    }
  }

  private boolean validateBet() {
    boolean isChecked = false;
    for (int i = 0; i < categories.size(); i++) {
      Category category = (Category) categories.elementAt(i);
      if (category.cb.isChecked()) {
        isChecked = true;
        break;
      }
    }
    if (!isChecked) {
      Global.alert.showAlert(this, GameAlert.OK_TYPE, "Bạn chưa chọn kèo");
      return false;
    }
    if (txtBetMoney.getText().length() == 0) {
      Global.alert.showAlert(this, GameAlert.OK_TYPE, "Bạn chưa đặt cược");
      return false;
    }
    
    int betMoney = NumberUtil.parseInt(txtBetMoney.getText());
    if (betMoney == NumberUtil.ERROR_VALUE) {
      Global.alert.showAlert(this, GameAlert.OK_TYPE, "Số $ đặt cược phải là số");
      return false;
    }
    
    if (betMoney > Global.currentUser.getMoney()) {
      Global.alert.showAlert3(this, GameAlert.OK_TYPE, StringArray.create1( "Số tiền đặt cược lớn hơn", "số tiền bạn đang có" ));
      return false;
    }
    return true;
  }

  private void request(int header, Vector parameters1) {
    DataPackage dataPackage = DataPackage.createDataPackage1(header);
    for (int i = 0; i < parameters1.size(); i++) {
      dataPackage.putString(parameters1.elementAt(i).toString());
    }
    Global.appClient.write(dataPackage);
    logAction.put(String.valueOf(currentAction), buildLogAction(header, parameters1));
  }

  private String buildLogAction(int requestType, Vector parameters1) {
    StringBuffer sb = new StringBuffer();
    sb.append(String.valueOf(requestType));
    sb.append(",");
    for (int i = 0; i < parameters1.size(); i++) {
      sb.append(parameters1.elementAt(i).toString());
      sb.append(",");
    }
    if (sb.toString().endsWith(",")) {
      sb.deleteCharAt(sb.length() - 1);
    }
    return sb.toString();
  }

  private void back() {
    currentAction--;
    dy = DrawUtils.getTopBarHeight() + 1;
    String values = (String) logAction.get(String.valueOf(currentAction));
    StringArray requestParams = GameStringUtils.split(values, ",");
    int header = NumberUtil.parseInt(requestParams.get(0));
    Vector param = new Vector();
    GameStringUtils.deleteElementAtStringArray(requestParams, 0);
    for (int i = 0; i < requestParams.len(); i++) {
      param.addElement(requestParams.get(i));
    }
    request(header, param);
  }

  private void clearCategory() {
    for (int i = 0; i < categories.size(); i++) {
      Category category = (Category) categories.elementAt(i);
      if (category.cb != null) {
        category.cb.setVisible(false);
        category.cb = null;
      }
    }
    categories.removeAllElements();
    txtBetMoney.clearText();
    txtBetMoney.setVisible(false);
    categoryIndex = 0;
    dy = DrawUtils.getTopBarHeight() + 1;
  }

  public void destroy() {
    logAction = null;
    currentAction = 1;
    formType = null;
    text8 = null;
    categories = null;
    currentAction = 1;
    dy = 0;
    txtBetMoney = null;
    parameters = null;
    text11 = null;
    txtBetMoney = null;
    PHASE_NAME = null;
    scrollBar = null;
    textView = null;
    buttonImage = null;
    betButtonSprite = null;
  }
}
